<template>
  <div class="login-register">
    <el-card class="card" shadow="hover">
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>
      <el-button class="back-button" @click="goHome">返回主页</el-button>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="form.confirmPassword" placeholder="请确认密码"></el-input>
        </el-form-item>

        <el-form-item v-if="!isLogin" label="用户昵称" prop="confirmPassword">
          <el-input type="text" v-model="form.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">{{ isLogin ? '登录' : '注册' }}</el-button>
          <el-button type="text" @click="toggleLoginRegister">{{ isLogin ? '去注册' : '去登录' }}</el-button>
        </el-form-item>
      </el-form>
      <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
    </el-card>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import {getUserInfo, login, register} from "@/api/user.js";

export default {
  data() {
    return {
      isLogin: true,
      errorMessage: '',
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        nickname: '',
      },
      rules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        confirmPassword: [{required: true, message: '请确认密码', trigger: 'blur'}],
        nickname: [{required: true, message: '请输入昵称', trigger: 'blur'}],
      },
    };
  },
  created() {
    // 根据路由参数设置是否显示登录或注册界面
    const param = this.$route.query.param; // 假设路由参数名为param
    if (param === '1') {
      this.isLogin = true;
    } else if (param === '2') {
      this.isLogin = false;
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isLogin) {
            this.login();
          } else {
            this.registerHandler();
          }
        } else {
          this.errorMessage = '请检查输入信息';
          return false;
        }
      });
    },
    login() {
      // 登录逻辑
      console.log('用户登录:', this.form.username);
      login({
        username: this.form.username,
        password: this.form.password
      }).then(res => {
        if (res.code === 200) {
          console.log('登录成功:', res);
          localStorage.setItem('token', res.data);
          getUserInfo().then(res => {
            console.log('获取用户信息成功:', res);
            localStorage.setItem('user', JSON.stringify(res.data));
            ElMessage.success('登录成功');
            this.$router.push({ path: '/' });
          })
        }
      }).catch(err => {
        this.errorMessage = '用户名或密码错误';
      });
    },
    registerHandler() {
      if (this.form.password !== this.form.confirmPassword) {
        this.errorMessage = '两次输入的密码不一致';
        return;
      }
      // 注册逻辑
      // console.log('用户注册:', this.form.username);
      register(this.form);
      this.resetForm();
    },
    toggleLoginRegister() {
      this.isLogin = !this.isLogin;
      this.errorMessage = '';
      this.resetForm();
    },
    goHome() {
      // 返回主页的逻辑，例如使用this.$router.push
      this.$router.push({path: '/'}); // 假设主页的路径为'/'
    },
    resetForm() {
      this.form.username = '';
      this.form.password = '';
      this.form.confirmPassword = '';
      this.form.nickname = '';
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style scoped>
.login-register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.card {
  width: 400px;
  padding: 20px;
  position: relative; /* 添加相对定位以便绝对定位的按钮 */
}

.back-button {
  position: absolute;
  right: 20px;
  top: 20px;
}

.error {
  color: red;
  margin-top: 10px;
}
</style>
